//
//  SopAddPicViewController.m
//  DigiOps
//
//  Created by app on 2018/7/31.
//  Copyright © 2018年 俞渊华. All rights reserved.
//

#import "SopAddPicViewController.h"
#import "SopAddPicViewCell.h"
#import "WBPopMenuModel.h"
#import "WBPopMenuSingleton.h"
#import "WBPopMenuView.h"
#import "CKHttpCommunicate.h"
#import "SopModel.h"

#import "AFOAuthCredential.h"
#import "GROAuth2SessionManager.h"
#import "pictureData.h"

@interface SopAddPicViewController ()<UIImagePickerControllerDelegate>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)UIImage *image1;
@property(nonatomic, strong)NSMutableDictionary *imageIndex;
@property(nonatomic,assign)int imageInt;

@property (nonatomic,strong) MBProgressHUD  *HUD;
@property (nonatomic,strong) NSMutableDictionary  *muti;
//@property (nonatomic,strong) NSMutableArray  *scoreArray1;

@end

@implementation SopAddPicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    CGRect labelFrame = CGRectMake(0.0, 0.0, SCREEN_WIDTH, 36.0);
    UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
    label.font = [UIFont boldSystemFontOfSize:18];
    label.numberOfLines = 2;
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = UITextAlignmentLeft;
    label.textColor = [UIColor whiteColor];
    //    label.shadowColor = [UIColor blackColor];
    //    label.shadowOffset = CGSizeMake(0.0, -1.0);
    label.lineBreakMode = UILineBreakModeMiddleTruncation;
    label.text=_label;
    self.navigationItem.titleView = label;
    
//    UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleBordered target:self action:@selector(clickEvent)];
//    [myButton setTintColor:[UIColor whiteColor]];
//    if (![MySingleton sharedMySingleton].finished){
//        self.navigationItem.rightBarButtonItem = myButton;
//    }
    [self.view addSubview:self.tableView];
    self.imageIndex=[NSMutableDictionary new];
    self.muti=[NSMutableDictionary new];
//    self.scoreArray1=[NSMutableArray new];
    
    //默认block方法：设置上拉加载更多
    self.navigationItem.hidesBackButton = YES;
    UIImage *image = [UIImage imageNamed:@"Back"];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 30, 44);
    backButton.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [backButton setImage:image forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftItemsSupplementBackButton = YES;
    //muti预先设置空值
    for (int i=0; i<3; i++) {
        [self.muti setValue:@"" forKey:[NSString stringWithFormat:@"%i",i]];
    }
    
    if (self.scoreArray.count>0) {

    NSArray* pic=[pictureData findWhere:@[@"picuuid",@"=",[self.scoreArray objectAtIndex:0]]];
    if (pic.count>0) {
        pictureData* pd=[pic objectAtIndex:0];
//        if (pd.picurl) {
//        }
//        else{
        self.muti=[pd.multi mutableCopy];
        
            if (pd.multi.count>1) {
                [self.scoreArray removeAllObjects];
                self.scoreArray=[[NSArray arrayWithArray:[pd.multi allValues]] mutableCopy];
                
                [self.tableView reloadData];
            }
//        }
    }
    }
    
}
-(void)goBack
{
    [self clickEvent];

}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
//    self.scoreArray=[NSMutableArray new];
//    self.scoreArray=@[@"list 1",@"list 2",@"list 3",@"4",@"5",@"6"];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}


-(void)searchAticle{
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (self.image1) {

    if (self.block) {
        self.block();
    }
    }
}

-(void)clickEvent{
    [self updateImageToServer:self.imageIndex];

}
- (NSArray *) titles {
    return @[@"提交"];
}

- (NSArray *) images {
    return @[@"right_menu_QR@3x",
             @"right_menu_addFri@3x",
             @"right_menu_multichat@3x",
             @"right_menu_sendFile@3x",
             @"right_menu_facetoface@3x",
             @"right_menu_payMoney@3x"];
}

/*upload images*/
- (void)updateImageToServer:(NSDictionary *)data
{
    NSArray* img=[data allValues];
//    [self sendImageWithImage:img];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.rt_navigationController popViewControllerAnimated:YES];
    });

    
}


-(NSData *)getDataWithString:(NSString *)string{
    
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    return data;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    return self.scoreArray.count;
        return 3;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    UITableViewCell* cell=[[UITableViewCell alloc] init];
//    cell.textLabel.text=[self.scoreArray objectAtIndex:indexPath.row];
//    cell.textLabel.textAlignment = NSTextAlignmentCenter;//文字居中
    //    cell.model=[RouteModel new];
    SopAddPicViewCell* cell=[SopAddPicViewCell cellWithTableView:tableView];
    cell.okButton.tag=indexPath.row;
    cell.closeButton.tag=indexPath.row;
    SopModel* model=[[SopModel alloc] init];
    model.ID=indexPath.row;
    cell.model=model;
    if (self.image1) {
        cell.imageTake.hidden=NO;
//        cell.closeButton.hidden=NO;
        if ([[self.imageIndex allKeys] containsObject:[NSString stringWithFormat:@"%i",indexPath.row]]) {
            cell.closeButton.hidden=NO;

            [cell.imageTake setImage:[self.imageIndex objectForKey:[NSString stringWithFormat:@"%i",indexPath.row]]];
            cell.addIcon.hidden=YES;
            //拍完的边框虚线改实线
//            [cell.okButton setImage:[self imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
            cell.okButton.layer.borderColor = [UIColor colorWithWhite:0.3 alpha:0.3].CGColor;//设置边框颜色
            cell.okButton.layer.borderWidth = 0.5f;//设置边框颜色
        }

    }
    if ([MySingleton sharedMySingleton].finished||![[UserInfo share].role.powerType isEqualToString:@"1"])
    {
        cell.imageTake.hidden=NO;
        if (indexPath.row<self.scoreArray.count) {
//        [cell.imageTake sd_setImageWithURL:[NSString stringWithFormat:@"%@/digiops%@",@"http://13.70.0.249:8082",[self.scoreArray objectAtIndex:indexPath.row]] ];
            NSArray* pic=[pictureData findWhere:@[@"picuuid",@"=",[self.scoreArray objectAtIndex:indexPath.row]]];
            if (pic.count>0) {
                pictureData* pd=[pic objectAtIndex:0];
                [cell.imageTake sd_setImageWithURL:[NSString stringWithFormat:@"%@/digiops%@",kBaseUrl,pd.picurl] ];
            }
            
        }
    }
    if (self.scoreArray.count>0) {
        cell.imageTake.hidden=NO;
        if (indexPath.row<self.scoreArray.count) {
            if ([[self.scoreArray objectAtIndex:indexPath.row] isEqualToString:@""]) {
            }
            else
            {
                NSArray* pic=[pictureData findWhere:@[@"picuuid",@"=",[self.muti objectForKey:[NSString stringWithFormat:@"%i",indexPath.row]]]];
                if (pic.count>0) {
                    pictureData* pd=[pic objectAtIndex:0];
                    if (pd.picurl) {
                        [cell.imageTake sd_setImageWithURL:[NSString stringWithFormat:@"%@/digiops%@",kBaseUrl,pd.picurl] ];
                    }
                    else{
                        [cell.imageTake setImage:[UIImage imageWithData:pd.picraw]];
                        //拍完的边框虚线改实线
//                        [cell.okButton setImage:[self imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
                        cell.okButton.layer.borderColor = [UIColor colorWithWhite:0.3 alpha:0.3].CGColor;//设置边框颜色
                        cell.okButton.layer.borderWidth = 0.5f;//设置边框颜色
                        cell.closeButton.hidden=NO;

                    }
                }
                else{
                    [cell.imageTake sd_setImageWithURL:[NSString stringWithFormat:@"%@/digiops%@",kBaseUrl,[self.scoreArray objectAtIndex:indexPath.row] ]];

                }

            }
        }
    }
    cell.block = ^(UIButton *sender) {
        self.imageInt=sender.tag;
        //禁止再拍
//        if (self.scoreArray.count>sender.tag) {
//            return ;
//        }
        if (![MySingleton sharedMySingleton].finished)
        {
            if (self.workModel.executeState==3) {
                NSLog(@"");
            }
            else
                [self addPic];
        }
    };
    cell.block1 = ^(UIButton *sender) {
        int a=sender.tag;
        [self delPic:(int)a];
        cell.addIcon.hidden=NO;

    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 100;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}
-(UIImage*) imageWithColor:(UIColor*)color

{
    CGRect rect = CGRectMake(0.0f,0.0f,1.0f,1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    
}


- (UITableView *)tableView{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableFooterView = [UIView new];
        tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
        view.backgroundColor = [UIColor whiteColor];
        UILabel* titleLabel = [[UILabel alloc]init];
        titleLabel.font = [UIFont xm_medium:17.0];
        titleLabel.numberOfLines = 1;
        titleLabel.textColor = [UIColor xm_jetblackColor];
        titleLabel.text=@"拍摄照片";
        
        [view addSubview:titleLabel];
                tableView.tableHeaderView=view;
        
        UIView * viewFoot = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
        viewFoot.backgroundColor = [UIColor whiteColor];
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        //        button.frame = CGRectMake(40, 100, SCREEN_WIDTH- 80, 30);
        button.backgroundColor = [UIColor lightGrayColor];
        [button setTitle:@"提交" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(submitRoute) forControlEvents:UIControlEventTouchUpInside];
        [viewFoot addSubview:button];
        //        tableView.tableFooterView=viewFoot;
        //        [button setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
        //        [button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        //        [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view).offset(18);
            make.left.equalTo(view.mas_left).offset(20);
        }];
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(viewFoot).offset(0);
            //            make.top.equalTo(view).offset(5);
            make.width.mas_equalTo(SCREEN_WIDTH-80);
            make.height.mas_equalTo(30);
            //            make.left.equalTo(view.mas_left).offset(20);
        }];
        _tableView = tableView;
    }
    return _tableView;
}
-(void)submitRoute
{
    
}
-(void)delPic:(int)a
{
//    self.image1=nil;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.imageIndex removeObjectForKey:[NSString stringWithFormat:@"%i",a]];
        [_tableView reloadData];
        [pictureData deleteWhere:@[@"picuuid",@"=",[self.muti objectForKey:[NSString stringWithFormat:@"%i",a]]]];
        [self.muti setObject:@"" forKey:[NSString stringWithFormat:@"%i",a]];
        [self.scoreArray replaceObjectAtIndex:a withObject:@""];
        if (a>0)
        {
        if (self.blockPicurl) {
            self.blockPicurl([self.muti objectForKey:[NSString stringWithFormat:@"%i",a-1] ]);
        }
        }
        else
        {
            int i;
            for (i=2;i>0;i--) {
                if ([self getDuplicateSubStrCountInCompleteStr:[self.muti objectForKey:[NSString stringWithFormat:@"%i",i]] withSubStr:@"-"]>2) {
                    break;
                }
            }
            if (self.blockPicurl) {
                self.blockPicurl([self.muti objectForKey:[NSString stringWithFormat:@"%i",i]]);
            }
            //
//            self.image1=nil;//没图也红色标
            int j=0;
            for (NSString* pic in [self.muti allValues]) {
                if ([self getDuplicateSubStrCountInCompleteStr:pic withSubStr:@"-"]>2) {
                    j++;
                }
            }
            if (j==0) {
                self.image1=nil;//没图也红色标
            }
        }
    });
}
- (void)addPic {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        [self cameraClick];
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        [self selectPhotos];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action) {
    }];
    
    [alertController addAction:cameraAction];
    //    [alertController addAction:albumAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark 拍摄、相册完成后要执行的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //得到图片
    UIImage* image = [UIImage imageWithData:UIImageJPEGRepresentation( [info objectForKey:UIImagePickerControllerEditedImage] ,0.2)];
    self.image1=image;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.imageIndex setObject:image forKey:[NSString stringWithFormat:@"%i",self.imageInt]];
        
        //
        pictureData* pd=[pictureData new];
        pd.picuuid=[self createUUID];
        pd.picraw=UIImagePNGRepresentation(image);
        NSLog(@"");
        
        [self.muti setObject:pd.picuuid forKey:[NSString stringWithFormat:@"%i",self.imageInt]];
        //删了再拍不出图
//        NSMutableArray* sopTemp=[NSMutableArray new];
//        for (int i=0;i< self.scoreArray.count;i++) {
//            if (i==self.imageInt) {
//            }
//            else
//                [sopTemp addObject:[self.scoreArray objectAtIndex:i]];
//        }
//        [self.scoreArray removeAllObjects];
//        self.scoreArray=sopTemp;
        if (self.imageInt<self.scoreArray.count)
            [self.scoreArray replaceObjectAtIndex:self.imageInt withObject:pd.picuuid];

        pd.multi=self.muti;
        [pd saveOrUpdateAsync:^(BOOL isSuccess) {
            if (self.blockPicurl) {
                self.blockPicurl(pd.picuuid);
            }
        }];
        [_tableView reloadData];
    });
    //    [addPhoto setImage:image];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)cameraClick {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;  //是否可编辑
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"您没有摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

- (void)selectPhotos {
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;//是否可以编辑
    //打开相册选择照片
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];
}
#pragma mark -- init MBProgressHUD
- (void)hudTipWillShow:(BOOL)willShow{
    if (willShow) {
        [self resignFirstResponder];
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        if (!_HUD) {
            _HUD = [MBProgressHUD showHUDAddedTo:keyWindow animated:YES];
            _HUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
            _HUD.progress = 0;
            _HUD.labelText = @"0%";
            _HUD.removeFromSuperViewOnHide = YES;
        }else{
            _HUD.progress = 0;
            _HUD.labelText = @"0%";
            [keyWindow addSubview:_HUD];
            [_HUD show:YES];
        }
    }else{
        [_HUD hide:YES];
    }
}
- (NSString *)createUUID
{
    
    // Create universally unique identifier (object)
    CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);
    NSString *uuidStr = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuidObject));
    CFUUIDBytes bytes = CFUUIDGetUUIDBytes(uuidObject);
    
    CFRelease(uuidObject);
    
    return uuidStr;
}
@end
